<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="工程量包代码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageName">
              <a-input v-model="model.packageCode" @change='packageCodeChange' placeholder="请输入工程量包代码"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="工程量包名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageName">
              <a-input v-model="model.packageName" placeholder="请输入工程量包名"></a-input>
            </a-form-model-item>
          </a-col>

<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="包格式" :labelCol="labelCol" :wrapperCol="wrapperCol">-->

<!--              <j-dict-select-tag v-model="model.packageFormat" dictCode="package_format" placeholder="请选择" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24" v-if="model.packageFormat && model.packageFormat === '_1553B'">-->
<!--            <a-form-model-item label="指令类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="instructionType">-->
<!--              <a-select v-model="model.instructionType" placeholder="请选择指令类型" :style="{ width: '100%' }">-->
<!--                <a-select-option value="00000">常规指令</a-select-option>-->
<!--                <a-select-option value="00001">数据块指令</a-select-option>-->
<!--              </a-select>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24" v-if="model.packageFormat && model.packageFormat === 'APPLICATION_LAYER'">-->
<!--            <a-form-model-item label="帧类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="frameType">-->
<!--              &lt;!&ndash;              <a-input v-model="model.frameType" placeholder="请输入帧类型(地到车填写001000)"></a-input>&ndash;&gt;-->
<!--              <j-dict-select-tag v-model="model.frameType" placeholder="请选择帧类型" dictCode="frame_type" />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24" v-if="model.packageFormat && model.packageFormat === 'APPLICATION_LAYER'">-->
<!--            <a-form-model-item label="虚拟信道" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="virtualChannelId">-->
<!--              <a-select v-model="model.virtualChannelId" placeholder="请选择虚拟信道" :style="{ width: '100%' }">-->
<!--                <a-select-option :value="item.id" v-for="item in virtualChannelList" :key="item.id">{{-->
<!--    item.virtualChannelName }}</a-select-option>-->
<!--              </a-select>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->

<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="绑定通道" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="channelId">-->
<!--              <a-select v-model="model.channelId" prop="channelId">-->
<!--                <a-select-option :value="item.id" :key="index" v-for="(item, index) in channelList">-->
<!--                  {{ item.channelName }}-->
<!--                </a-select-option>-->
<!--              </a-select>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="收发类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="actionType">-->
<!--              <j-dict-select-tag-->
<!--                type="list"-->
<!--                v-model="model.actionType"-->
<!--                dictCode="actionType"-->
<!--                placeholder="请选择收发类型"-->
<!--              />-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->

<!--          <a-col :span="24">-->
<!--            <a-form-model-item label="回调bean名称" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <a-input v-model="model.callBackBeanName" placeholder="请输入回调bean名称"></a-input>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->

          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="note">
              <a-input v-model="model.note" placeholder="请输入备注"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- <a-row>
          <a-col :span="24">
            <a-button class="editable-add-btn" @click="handleAdd"> 新增工程量 </a-button>
            <a-table bordered :data-source="model.dataSource" :columns="columns">
              <template slot="packageGridId" slot-scope="text, record">
                <div>
                  <a-select
                    v-if="record.editable1"
                    placeholder="请选择"
                    @change="(e) => handleChange1(e, record.key, 'packageGridId')"
                  >
                    <a-select-option v-for="mode in packageGridIdList" :key="mode.id" :value="mode.id">
                      {{ mode.gridName }}
                    </a-select-option>
                  </a-select>
                  <template v-else>
                    {{ formatName(text, 'packageGridId') }}
                  </template>
</div>
</template>
<template slot="packageInfoId" slot-scope="text, record">
                <div>
                  <div v-if="record.editable1">
                    <a-select placeholder="请选择" @change="(e) => handleChange1(e, record.key, 'packageInfoId')">
                      <a-select-option v-for="mode in PackageInfoList" :key="mode.id" :value="mode.id">
                        {{ mode.packageName }}
                      </a-select-option>
                    </a-select>
                  </div>

                  <template v-else>
                    {{ formatName(text, 'packageInfoId') }}
                  </template>
</div>
</template>
<template slot="orderd" slot-scope="text, record">
                <div>
                  <a-input
                    v-if="record.editable1"
                    style="margin: -5px 0"
                    :value="text"
                    @change="(e) => handleChange1(e.target.value, record.key, 'orderd')"
                  />
                  <template v-else>
                    {{ text }}
                  </template>
</div>
</template>
<template slot="operation" slot-scope="text, record">
                <a-popconfirm
                  style="margin-right: 5px"
                  v-if="dataSource.length"
                  title="Sure to delete?"
                  @confirm="() => onDelete(record.key)"
                >
                  <a href="javascript:;">删除</a>
                </a-popconfirm>
                <span v-if="record.editable1">
                  <a @click="() => save(record.key)" style="margin-right: 5px">保存</a>
                  <a-popconfirm title="Sure to cancel?" @confirm="() => cancel(record.key)" style="margin-right: 5px">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span v-else style="margin-right: 5px">
                  <a :disabled="editingKey !== ''" @click="() => editK(record.key)">编辑</a>
                </span>
                <div class="editable-row-operations"></div>
              </template>
</a-table>
</a-col>
</a-row>-->
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
const EditableCell = {
  template: `
      <div class="editable-cell">
        <div v-if="editable" class="editable-cell-input-wrapper">
          <a-input :value="value" @change="handleChange" @pressEnter="check" /><a-icon
            type="check"
            class="editable-cell-icon-check"
            @click="check"
          />
        </div>
        <div v-else class="editable-cell-text-wrapper">
          {{ value || ' ' }}
          <a-icon type="edit" class="editable-cell-icon" @click="edit" />
        </div>
      </div>
    `,
  props: {
    text: String,
  },

  data() {
    return {
      value: this.text,
      editable: false,
    }
  },
  methods: {
    handleChange(e) {
      const value = e.target.value
      this.value = value
    },
    check() {
      this.editable = false
      this.$emit('change', this.value)
    },
    edit() {
      this.editable = true
    },
  },
}
// const data = []
// for (let i = 0; i < 100; i++) {
//   data.push({
//     key: i.toString(),
//     name: `Edrward ${i}`,
//     packageInfoId: 32,
//     orderd: `London Park no. ${i}`,
//   })
// }
export default {
  name: 'NmcPackageInfoForm',
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  components: {
    EditableCell,
  },
  data() {
    const validateFrameType = (rule, value, callback) => {
      let reg = /^[0-1]{6}$/
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error('请输入一个6位0/1的数'))
      }
    };
    return {
      virtualChannelList: [],
      model: {
        // 帧类型默认是地到车：001000
        frameType: "001000",
        packageFormat: "APPLICATION_LAYER",
        // dataSource: [
        //   {
        //     key: '0',
        //     packageGridId: '',
        //     packageInfoId: '',
        //     orderd: '',
        //     editable1: true,
        //   },
        // ],
      },
      editingKey: '',
      cacheData: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        frameType: [
          { required: false, message: '请输入虚拟信道编码!' },
          { validator: validateFrameType, target: 'blur' },
        ],
        channelId: [{ required: true, message: '请选择', trigger: 'change' }],
        actionType: [{ required: true, message: '请选择', trigger: 'change' }],
      },
      channelList: [],
      url: {
        add: '/grid/nmcPackageInfo/add',
        edit: '/grid/nmcPackageInfo/edit',
        queryById: '/grid/nmcPackageInfo/queryById',
        PackageGridlist: '/grid/nmcPackageGrid/list',
        PackageInfoList: '/grid/nmcPackageInfo/list',
        virtualChannelList: "/virtualChannel/nmcVirtualChannel/list",
        channelList: '/channel/nmcChannelInfo/list',
      },
      dataSource: [
        {
          key: '0',
          packageGridId: '',
          packageInfoId: '',
          orderd: '',
        },
      ],
      count: 1,
      packageGridIdList: [],
      columns: [
        {
          title: '工程量',
          dataIndex: 'packageGridId',
          width: '25%',
          scopedSlots: { customRender: 'packageGridId' },
        },
        {
          title: '工程量包',
          dataIndex: 'packageInfoId',
          width: '15%',
          scopedSlots: { customRender: 'packageInfoId' },
        },
        {
          title: '组包排序',
          dataIndex: 'orderd',
          width: '40%',
          scopedSlots: { customRender: 'orderd' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 180,
          scopedSlots: { customRender: 'operation' },
        },
      ],
      PackageInfoList: [],
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    // this.cacheData = [...this.model.dataSource]
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.loadChannel();
  },
  methods: {
    packageCodeChange() {
      this.model.packageName = this.model.packageCode;
    },
    loadChannel() {
      getAction(this.url.channelList, { pageSize: -1 }).then((res) => {
        if (res.success) {
          console.log(res)
          this.channelList = res.result.records
        }
      })
      // this.channelList=res.re
    },
    getList() {
      getAction(this.url.PackageGridlist).then((res) => {
        // console.log(res)
        this.packageGridIdList = res.result.records
      })
      getAction(this.url.PackageInfoList).then((res) => {
        // console.log(res)
        this.PackageInfoList = res.result.records
      })
      getAction(this.url.virtualChannelList, { pageSize: -1 }).then((res) => {
        // console.log(res)
        this.virtualChannelList = res.result.records
      })
    },
    editK(key) {
      console.log(key)
      const newData = [...this.model.dataSource]
      const target = newData.find((item) => key === item.key)
      this.editingKey = key
      if (target) {
        target.editable1 = true
        this.model.dataSource = newData
      }
      console.log(target)
    },
    save(key) {
      const newData = [...this.model.dataSource]
      const newCacheData = [...this.cacheData]
      const target = newData.find((item) => key === item.key)
      const targetCache = newCacheData.find((item) => key === item.key)
      console.log(target)
      if (target && targetCache) {
        delete target.editable1
        this.model.dataSource = newData
        Object.assign(targetCache, target)
        this.cacheData = newCacheData
      }
      this.editingKey = ''
    },
    cancel(key) {
      const newData = [...this.model.dataSource]
      const target = newData.find((item) => key === item.key)
      this.editingKey = ''
      if (target) {
        Object.assign(
          target,
          this.cacheData.find((item) => key === item.key)
        )
        delete target.editable1
        this.model.dataSource = newData
      }
    },
    handleChange1(value, key, column) {
      console.log(value, key, column)
      const newData = [...this.model.dataSource]
      const target = newData.find((item) => key === item.key)
      if (target) {
        target[column] = value
        this.model.dataSource = newData
      }
    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.model.dataSource]
      const target = dataSource.find((item) => item.key === key)
      if (target) {
        target[dataIndex] = value
        this.model.dataSource = dataSource
      }
    },
    onDelete(key) {
      const dataSource = [...this.model.dataSource]
      this.model.dataSource = dataSource.filter((item) => item.key !== key)
    },
    handleAdd() {
      const { count, dataSource } = this
      const newData = {
        key: count,
        packageGridId: '',
        packageInfoId: '',
        orderd: '',
        editable1: true,
      }
      console.log(count)
      this.model.dataSource = [...dataSource, newData]
      this.count = count + 1

      this.cacheData = [...this.model.dataSource]
    },
    formatName(text, type) {
      if (type == 'packageGridId') {
        return this.packageGridIdList.find((i) => i.id == text).gridName
      } else if (type == 'packageInfoId') {
        return this.PackageInfoList.find((i) => i.id == text).packageName
      }
    },
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.getList()
      this.visible = true
    },

    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },

  },
}
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
